import { memo } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link } from 'react-router-dom';
import { Avatar, Button, Image, message, Popconfirm, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { API_BASEURL } from '@/constants/api';
import { resAddOrCancelCollect, resCollect } from '@/services/collect';
import { resAddOrCancelFollow, resFollow } from '@/services/follow';
import { userStore } from '@/store/userStore';
import { useAntdTable } from 'ahooks';
import { isString } from 'lodash';
import { useRecoilValue } from 'recoil';
import ProfileContainer from '@/components/ProfileContainer';
import { formatTime, formatUrl } from '@/utils/format';

const createColumns = (refresh: () => void): ColumnsType<API.CollectStruct> => {
  return [
    {
      title: <div className={' font-bold'}>图片</div>,
      dataIndex: ['goods', 'cover'],
      align: 'center',
      render: (cover) =>
        cover &&
        isString(cover) && (
          <Image src={formatUrl(cover)} alt="" width={40} height={64} />
        ),
    },
    {
      title: <div className={' font-bold'}>商品名称</div>,
      dataIndex: ['goods', 'title'],
      align: 'center',
      width: 150,
      render: (title, { goods }) => (
        <Link to={`/goods_detail/` + goods?.id}>{title}</Link>
      ),
    },
    {
      title: <div className={'font-bold'}>收藏时间</div>,
      dataIndex: 'created_at',
      align: 'center',
      render: (create_at) => <div>{formatTime(create_at)}</div>,
    },
    {
      title: <div className={'font-bold'}>操作</div>,
      align: 'center',
      render: (_, collect) => (
        <Popconfirm
          title={'您确定要取消此关注吗'}
          cancelText="取消"
          okText="确定"
          onConfirm={() => {
            resAddOrCancelCollect(collect.goods_id).then(() => {
              message.success('取消收藏成功！');
              refresh();
            });
          }}
        >
          <Button type={'link'}>取消收藏</Button>
        </Popconfirm>
      ),
    },
  ];
};

const CollectsPage: FC<PropsWithChildren<{}>> = () => {
  const user = useRecoilValue(userStore);
  const { tableProps, pagination } = useAntdTable(
    ({ pageSize, current }) => {
      return resCollect(user.id, {
        pageSize,
        current,
      });
    },
    { cacheKey: 'useCollectCache' }
  );

  const refresh = () => {
    pagination.changeCurrent(pagination.current);
  };

  const columns = createColumns(refresh);
  return (
    <ProfileContainer title={'我的收藏'}>
      <Table columns={columns} rowKey="id" {...tableProps} />
    </ProfileContainer>
  );
};

export default memo(CollectsPage);
